<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyAllocationSaleListTable;
use App\Http\Models\Mysql\SsyAllocationSaleTable;
use Illuminate\Console\Command;

class repairData extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:repairData {--type=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '修复数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $type = $this->option("type") ?? "";
        switch ($type){
            case "lendsale":
                $this->lendSale();
                break;
        }
    }

    //修复重复导入数据
    public function lendSale()
    {
        $list = (new SsyAllocationSaleListTable())->get(['allocation_number'])->toArray();
        foreach($list as $item){
            $repeatData = [];
            $orders = (new SsyAllocationSaleTable())->where('allocation_number', $item['allocation_number'])
                ->get(['id', 'allocation_number', 'source_allocation_number', 'sku_code', 'num'])->toArray();
            foreach($orders as $order){
                $repeatData[$item['allocation_number'].":".$order['source_allocation_number'].":".$order['sku_code']][] = $order;
            }
            foreach ($repeatData as $data){
                if(count($data) <= 1){
                    continue;
                }
                $num = array_sum(array_column($data, 'num'));
                $saleItem = array_shift($data);
                (new SsyAllocationSaleTable())->updateData($saleItem['id'], ['num' => $num]);
                (new SsyAllocationSaleTable())->deleteData(array_column($data, 'id'));
            }
        }
    }
}
